﻿Imports System.Net
Imports System.IO

Public Class FileDownload
    Private mPercentage As Integer = 0
    Private mCPercentage As Integer = -1
    Private mDataString As String

    Public Event PercentageChanged(Percentage As Integer)
    Public Event DownLoadCompleted(Success As Boolean)

    Private mClient As WebClient
    ReadOnly Property DataString As String
        Get
            Return mDataString
        End Get
    End Property
    Public Sub DownLoadFileToDestination(DownURI As String, DestinationPath As String)
        Using mClient As New WebClient()
            AddHandler mClient.DownloadProgressChanged, AddressOf client_ProgressChanged
            AddHandler mClient.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
            mClient.DownloadFileAsync(New Uri(DownURI), DestinationPath)
        End Using
    End Sub
    Private Sub client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
        Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
        mPercentage = CInt(bytesIn / totalBytes * 100)
        If mPercentage <> mCPercentage Then
            RaiseEvent PercentageChanged(mPercentage)
            mCPercentage = mPercentage
        End If
    End Sub
    Private Sub client_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
        RemoveHandler mClient.DownloadProgressChanged, AddressOf client_ProgressChanged
        RemoveHandler mClient.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
        RaiseEvent DownLoadCompleted(True)
    End Sub
    Public Async Function DownloadFileToString(DownURI As String) As Task(Of SAEventArgs)
        mDataString = ""
        Using client As New WebClient
            Try
                Dim data = Await client.OpenReadTaskAsync(New Uri(DownURI))
                Dim reader As StreamReader = New StreamReader(data)
                mDataString = reader.ReadToEnd
                Return New SAEventArgs(mDataString, SAEventArgs.Results.Success)
            Catch ex As Exception
                Return New SAEventArgs(ex.Message, SAEventArgs.Results.GeneralFailure)
            End Try
        End Using
    End Function
End Class
